
package com.logic.landseaserver.ws;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.logic.landseaserver.common.LandeaConstants;
import com.logic.landseaserver.service.ICustomerCardService;
import com.logic.landseaserver.ws.dto.*;
import com.logic.landseaserver.ws.request.CreateOffLineContractsReq;
import com.logic.landseaserver.ws.request.ReleaseRoomReq;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.logic.common.enums.HttpCodeEnum;
import com.logic.common.exception.BusinessException;
import com.logic.common.util.CommonResult;
import com.logic.common.util.CommonResultMap;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.exception.LandseaBusinessException;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.util.ConstantChar;
import com.logic.landseaserver.common.util.DateUtil;
import com.logic.landseaserver.models.payment.PaymentConstant.PayType;
import com.logic.landseaserver.service.IDepositService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @Author: jack
 * @Date: 2017/6/8
 * @Description: 预定
 */
@Path("/deposit")
@Api(value="deposit")
public class DepositRest {

	@Autowired
	private IDepositService iDepositServiceImpl;

    @Autowired
    private ICustomerCardService customerCardService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
	
    //查询详情
	@GET
    @Path("/{depositId}")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Get deposit detail ", position = 4)
    public Response getDeatilById(
            @ApiParam(value = "param", required = true) @PathParam("depositId") Integer depositId) {
        CommonResultMap map = new CommonResultMap();
        try {
            map.setData(iDepositServiceImpl.get(depositId));
        } catch (BusinessException e) {
            logger.error(" get depositId error.", e);
            map.setResult(CommonResult.BUSINESS_EXCEPTION, e.getMessage());
        } catch (Exception e) {
            logger.error(" get depositId error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }


    //查询详情
    @PUT
    @Path("/releaseRoom")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Get deposit detail ", position = 4)
    public Response release(@ApiParam(value = "param", required = true) ReleaseRoomReq depositReq) {
        CommonResultMap map = new CommonResultMap();
        try {
            iDepositServiceImpl.releaseRoom(depositReq) ;
            map.setResult(CommonResult.SUCCESS, "Create success");
        } catch (BusinessException e) {
            logger.error("releaseRoom error.", e);
            map.setResult(CommonResult.BUSINESS_EXCEPTION, e.getMessage());
        } catch (Exception e) {
            logger.error("releaseRoom error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }


    //查询详情
    @GET
    @Path("/getPDFImg/{depositId}")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Get deposit pdf img by deposit id ", position = 6)
    public Response getImgById(
            @ApiParam(value = "param", required = true) @PathParam("depositId") Integer depositId) {
        CommonResultMap map = new CommonResultMap();
        try {
            map.setData(iDepositServiceImpl.queryPDFImg(depositId));
            map.setResult(CommonResult.SUCCESS, "Create success");
        } catch (BusinessException e) {
            logger.error("getPDFImg error.", e);
            map.setResult(CommonResult.BUSINESS_EXCEPTION, e.getMessage());
        } catch (Exception e) {
            logger.error("getPDFImg error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
	//增加
	@POST
	@Path("/createDeposit")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "Create a new deposit",position = 1)
	public Response createDeposit(@ApiParam(value = "param", required = true) DepositDTO depositDTO) {
		CommonResultMap map = new CommonResultMap();
        try {
        	int id = iDepositServiceImpl.insertDeposit(depositDTO);
        	depositDTO.setId(id);
            map.setData(depositDTO);
            map.setResult(CommonResult.SUCCESS, "Create success");
        } catch (BusinessException e) {
            logger.error("createDeposit error.", e);
            map.setResult(CommonResult.BUSINESS_EXCEPTION, e.getMessage());
        } catch (Exception e) {
            logger.error("createDeposit error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}
	
	//查询所有信息
	@POST
	@Path("/list")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "list Deposit",position = 2)
	public Response list(@ApiParam(value = "param", required = true) QueryUtil queryUtil){
        CommonResultMap map = new CommonResultMap();
        List<DepositDTO> depositDTOList = null;
        try {
            queryUtil.getPagingTool().calculateStartIndex();
            depositDTOList = (List<DepositDTO>)iDepositServiceImpl.query(queryUtil);
            Integer totalCount = queryUtil.getPagingTool().getTotalNum();
            map.setData(depositDTOList);
            map.setResultTotalCount(totalCount);
            map.setResult(CommonResult.SUCCESS);

        } catch (Exception e) {
            logger.error("list error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();		
	}

	//删除
    @DELETE
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "logic delete deposit by set deleted", position = 3)
    public Response logicDelete(@ApiParam(value = "param", required = true) @QueryParam("id") Integer id) {
        CommonResultMap map = new CommonResultMap();
        try {
        	iDepositServiceImpl.deleteDeposit(id);
            map.setResult(CommonResult.SUCCESS,"delete activity");
        } catch (Exception e) {
            logger.error("logicDelete error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
	
    //编辑
    @PUT
	@Path("/editDeposit")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "Edit Deposit ")
    public Response editDeposit(@ApiParam(value = "param", required = true) DepositDTO depositDTO) {
        CommonResultMap map = new CommonResultMap();
        try {
        	iDepositServiceImpl.editDeposit(depositDTO);
            map.setResult(CommonResult.SUCCESS,"edit Deposit");
        } catch (Exception e) {
            logger.error("editDeposit error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    //获取pdf详情
    @GET
    @Path("/getDipositPdfInfo/{depositId}")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Get deposit pdf detail ", position = 4)
    public Response getPdfDeatilById(
          @ApiParam(value = "param", required = true) @PathParam("depositId") Integer depositId) {
    	CommonResultMap map = new CommonResultMap();
    	try {
    		map.setData(iDepositServiceImpl.getPdfDitail(depositId));
    	} catch (Exception e) {
    	    logger.error("getPdfDeatilById error.", e);
    	}
    	return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    //生成pdf
    @PUT
    @Path("/productDipositPdf")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "生成pdf", position = 12)
    public Response productDipositPdf(
            @ApiParam(value = "param", required = true) @QueryParam("depositId") int id) {
        CommonResultMap map = new CommonResultMap();
        Integer fileid = null;
        try {
            DepositPdfDTO deposit = new DepositPdfDTO();
            deposit.setId(id);
            fileid = iDepositServiceImpl.productDipositPdf(deposit);
            HashMap resultmap = new HashMap();
            resultmap.put("fileId", fileid);
            map.setData(resultmap);
            map.setResult(CommonResult.SUCCESS);
        } catch (LandseaBusinessException e) {
            logger.error("productDipositPdf LandseaBusinessException.", e);
            map.setResult(CommonResult.BUSINESS_EXCEPTION, e.getMessage());
        } catch (Exception e) {
            logger.error("productDipositPdf error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @POST
    @Path("/cancleComeDue")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "测试定金状态为已过期", position = 13)
    public Response updateDepositDue() {
        CommonResultMap map = new CommonResultMap();
        try {
            String comeDueDate = DateUtil.getInstence().convertDate(DateUtils.addDays(new Date(), -1));
            iDepositServiceImpl.cancleComeDueDeposit(comeDueDate);
            map.setResult(CommonResult.SUCCESS);
        } catch (Exception e) {
            logger.error("updateDepositDue error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
    //支付定金
    @POST
	@Path("/getWeBankPay")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "微众支付接口 【 收单 & PayType.WEBANK_MOBILE(收银台)】")
	public Response getWeBankPay(
			@ApiParam(value = "param", required = true) DepositWeBankPayReqDTO payinfo) {
		CommonResultMap map = new CommonResultMap();
		
		logger.info("DepositRequest|getWeBankPay|Request|" + payinfo.toString());
		
		try {
			WeBankPayRespDTO paydto = iDepositServiceImpl.getDepositWeBankPay(payinfo);
			map.setData(paydto);
			map.setResult(CommonResult.SUCCESS);
		}
		catch (LandseaException e)
		{
		    map.setResult(CommonResult.ERROR, e.getErrorDesc());
		}
		catch (Exception e) {
		    logger.error("getWeBankPay error.", e);
			map.setResult(CommonResult.ERROR, e.getMessage());
		}
		return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}
	    
    //POS端支付成功后生成预定编号。
  	@POST
  	@Path("/getDepositStatus")
  	@Produces(MediaType.APPLICATION_JSON)
  	@Consumes(MediaType.APPLICATION_JSON)
  	@ApiOperation(value = "POS端支付成功后生成预定编号{depositId:xxx}",position = 6)
  	public Response getDepositStatus(@ApiParam(value = "param", required = true) Map pmap) {
  	     CommonResultMap map = new CommonResultMap();
  	     Map<String, Object> result = new HashMap<String, Object>();
  	     List<BillSelectAllDTO> billDTOList = null;
  	     try {
  	    	 HashMap hm = (HashMap)pmap;
  	    	 String conStr = hm.get("depositId").toString();
  	    	 Integer conIn = Integer.parseInt(conStr);
  	    	 iDepositServiceImpl.updateDepostiId(conIn);
  	    	 result.put("STATUS", 0);
             map.setData(result);
          } catch (Exception e) {
              logger.info("getConBillStatus Exception", e);
  			map.setResult(CommonResult.BUSINESS_EXCEPTION, e.getMessage());
  			result.put("STATUS", -1);
          }
          return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();		
  	}
    @POST
    @Path("/clearComeDue")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "删除未交费的定金", position = 14)
    public Response clearDepositDue() {
        CommonResultMap map = new CommonResultMap();
        try {
            Date date = DateUtils.addMinutes(new Date(), -ConstantChar.deposit_clear_time);
            iDepositServiceImpl.clearDeposit(date);
            map.setResult(CommonResult.SUCCESS);
        } catch (Exception e) {
            logger.error("clearDepositDue error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @GET
    @Path("/getDepositList")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Get depositlist for wechat user ", position = 6)
    public Response getDepositListForWechat() {
        CommonResultMap map = new CommonResultMap();
        try {
            map.setData(iDepositServiceImpl.queryListForWechat());
        }catch (BusinessException e) {
            logger.error("getDepositListForWechat BusinessException: ", e);
            map.setResult(CommonResult.BUSINESS_EXCEPTION, e.getMessage());
        }  catch (Exception e) {
            logger.error("getDepositListForWechat error.", e);
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
    
	//同步预定支付信息
	@POST
	@Path("/updatePayStatus")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "同步预定支付信息",position = 1)
	public Response updatePayStatus() {
		CommonResultMap map = new CommonResultMap();
        try {
        	String result = iDepositServiceImpl.updatePayStatus();
        	map.setData(result);
            map.setResult(CommonResult.SUCCESS, "Clear success");
        } catch (Exception e) {
            logger.error("updatePayStatus error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

    @POST
    @Path("/testCreatePDFImg")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "测试生成PDF对应的图片", position = 8)
    public Response testCreatePDFImg()
    {
        CommonResultMap map = new CommonResultMap();
        Map<String, Object> result = new HashMap<String, Object>();
        try
        {
            iDepositServiceImpl.testCreatePDFImg();
            result.put("STATUS", 0);
            map.setData(result);
        }
        catch (Exception e)
        {
            logger.info("testCreatePDFImg Exception" + e.getMessage());
            map.setResult(CommonResult.BUSINESS_EXCEPTION, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    //
    @PUT
    @Path("/posCallBack")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "posCallBack POS支付成功后回调")
    public Response posCallBack(@ApiParam(value = "param", required = true) DepositDTO depositDTO) {
        CommonResultMap map = new CommonResultMap();
        try {
            iDepositServiceImpl.posCallBack(depositDTO);
            map.setResult(CommonResult.SUCCESS,"posCallBack Deposit update ok");
        } catch (Exception e) {
            logger.error("posCallBack editDeposit error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @PUT
    @Path("/updateVersion/{depositId}")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "租客信息变更->预定变更", position = 13)
    public Response updateDipositPdf(
            @ApiParam(value = "param", required = true) @PathParam("depositId") Integer depositId) {
        CommonResultMap map = new CommonResultMap();
        Integer fileid = null;
        try {
            iDepositServiceImpl.updateVersion(depositId);
            map.setResult(CommonResult.SUCCESS);
        } catch (LandseaBusinessException e) {
            logger.error("updateVersion LandseaBusinessException.", e);
            map.setResult(CommonResult.BUSINESS_EXCEPTION, e.getMessage());
        } catch (Exception e) {
            logger.error("updateVersion error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @POST
    @Path("/getChangeVersionCount")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "获得合同历史变更记录的总数", position = 14)
    public Response getChangeVersionCount(@ApiParam(value = "param", required = true) Map pmap) {
        CommonResultMap map = new CommonResultMap();
        try {
            String prjId =  (String)pmap.get("prjId");
            HashMap resultMap = new HashMap();
            if(StringUtils.isEmpty(prjId)){
                resultMap.put("count",iDepositServiceImpl.getChangeVersionCount(null));
            }else{
                resultMap.put("count",iDepositServiceImpl.getChangeVersionCount(Integer.parseInt(prjId)));
            }
            map.setData(resultMap);
            map.setResult(CommonResult.SUCCESS);
        }catch (Exception e) {
            logger.error("queryHistoryVersions error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @PUT
    @Path("/updateAuthCode")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "预定编辑->授权码修改 ")
    public Response updateAuthCode(@ApiParam(value = "param", required = true) DepositDTO depositDTO) {
        CommonResultMap map = new CommonResultMap();
        try {
            iDepositServiceImpl.updateAuthCode(depositDTO);
            map.setResult(CommonResult.SUCCESS, "updateAuthCode success");
        } catch (BusinessException e) {
            logger.error("updateAuthCode error", e);
            map.setResult(CommonResult.BUSINESS_EXCEPTION, e.getMessage());
        } catch (Exception e) {
            logger.error("updateAuthCode error", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

    @GET
    @Path("/queryCardInfo/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "query detail customer card info by deposit id", position = 12)
    public Response queryCardInfo(
            @ApiParam(value = "param", required = true) @PathParam("id") Integer id) {
        CommonResultMap map = new CommonResultMap();
        try {
            HashMap queryMap= new HashMap();
            queryMap.put("mainId",id);
            queryMap.put("mainType", LandeaConstants.QueryUesdCodeType.DEPOSIT);
            map.setData(customerCardService.queryCardInfo(queryMap));
            map.setResult(CommonResult.SUCCESS, "queryCardInfo success");
        } catch (Exception e) {
            logger.error("queryCardInfo error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }
}
